package ru.mcfr.oxygen.updater;

import ru.mcfr.oxygen.updater.installer.FileInstaller;
import ru.mcfr.oxygen.updater.web.XMLBasedUpdater;
import sun.net.www.protocol.http.HttpURLConnection;

import java.awt.*;
import java.io.File;
import java.util.Calendar;
import java.util.Map;

//download from server zip file and unpack her to temp folder
public class UpdateProcessor extends PropertiesContainer{
	
	private static UpdateProcessor instance;
	
	static private void showError(String msg){
		System.err.println(msg);
	}

	public static UpdateProcessor getInstance(String main_path, String super_system){
		if (instance == null)
            synchronized (UpdateProcessor.class) {instance = new UpdateProcessor(main_path + File.separator + "settings.xml");}

        instance.setMainPath(main_path);
		instance.setSuperPath(super_system);
		instance.save();
		
		return instance;
	}

	private UpdateProcessor(String path) {
        super(path);
        this.window = new SettingsWindowImpl();
    }

    public void setMainPath(String path){setProperty("path-to-main",path);}

    public void setSuperPath(String path){setProperty("path-to-super",path);}

    public String installUpdates(String scriptName){

        return "";
    }

    private SettingsWindowImpl window = null;

	public void showSettingsDialog(){
		showSettingsDialog(null);
	}
	
	public void showSettingsDialog(Object parentFrame){
		window.setLocationRelativeTo((Component) parentFrame);
		window.setVisible(true);
		window.loadToWindow();
	}

    private String doUpdate(){
        setProperty("path-to-plugin", getProperty("path-to-super") + File.separator + "plugins");
        setProperty("path-to-framework", getProperty("path-to-super") + File.separator + "frameworks");
        save();
        XMLBasedUpdater xmlBasedUpdater = new XMLBasedUpdater(this);
        HttpURLConnection connection = xmlBasedUpdater.connectToURL(getProperty("server-url", "") + "/updates.xml");
        if (connection != null) {
            if (xmlBasedUpdater.checkUpdates(connection)) {
                Map<String,String> res = xmlBasedUpdater.downloadUpdatesTo("updates");
                String msg = "Используется последняя версия.";
                int success = 0, notsiccess = 0;
                for (String key : res.keySet()){
                    try{
                        String pathToInstall = getProperty("path-to-super") + File.separator + key;
                        new File(pathToInstall).mkdirs();
                        new FileInstaller(pathToInstall).doInstallation(res.get(key));
                        System.out.println("Install <" + res.get(key) + "> to <" + pathToInstall + ">");
                        success += 1;
                    } catch (Exception e){
                        System.err.println(e.getMessage());
                    }
                    msg = "Обновлено успешно. " + success + " из " + res.size();
                }
                return msg;
            } else
                return "Нет обновлений";
        } else
            return "Сервер не доступен";
    }

    public String run(){

        long timeLastUpdate = Long.valueOf(getProperty("last-update", "0"));
        long timeThis = Calendar.getInstance().getTimeInMillis();
        long period = 1000 * 60 * Long.valueOf(getProperty("update-per-minutes", "120"));
        if (timeThis - timeLastUpdate < period)
            return "Ожидание";

        setProperty("last-update", String.valueOf(Calendar.getInstance().getTimeInMillis()));
        save();

        return doUpdate();
    }
	
	@SuppressWarnings("serial")
	private class SettingsWindowImpl extends SettingsWindow {

		public SettingsWindowImpl() {
			super();
			loadSettings();
		}
		
		private void loadSettings(){
			oXygenPath.setText(getProperty("path-to-super", ""));
			proxyUserPass.setText(getProperty("proxy-user-password", ""));
			proxyUserName.setText(getProperty("proxy-user-name", ""));
			proxyServer.setText(getProperty("proxy-server",""));
			urlUpdateServer.setText(getProperty("server-url",""));
			
			if (getProperty("use-proxy","").equals("true"))
				useProxyCheck.setSelected(true);
			else
				useProxyCheck.setSelected(false);
		}
		
		private void saveSettings() {
			setProperty("path-to-super", oXygenPath.getText());
			setProperty("server-url", urlUpdateServer.getText());
			setProperty("proxy-server", proxyServer.getText());
			setProperty("proxy-user-name", proxyUserName.getText());
			setProperty("proxy-user-password", String.copyValueOf(proxyUserPass.getPassword()));
			if (useProxyCheck.isSelected()) setProperty("use-proxy", "true");
			else setProperty("use-proxy", "false");
		}
		
		protected void jCheckUpdatesButtonAction(java.awt.event.ActionEvent evt) {
            checkUpdatesButton.setText(doUpdate());
		}
		
		protected void jCloseButtonAction(java.awt.event.ActionEvent evt) {
			saveSettings();
            save();
			setVisible(false);
		}
		
		public void loadToWindow(){
			loadSettings();
		}
	}
}
